package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;
    /**
     * 根据id查询商铺信息
     * @param id 商铺id
     * @return 商铺详情数据
     */
    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
                this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//
//        //缓存击穿（基于互斥锁）
//        Shop shop = queryWithMutex(id);

//        //缓存击穿（基于逻辑过期时间）
//        Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
        //返回
        if(shop == null){
            return Result.fail("未查询到相关店铺");
        }
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //缓存击穿(逻辑过期时间）
//    public Shop queryWithLogicalExpire(Long id){
//        String key = RedisConstants.CACHE_SHOP_KEY + id;
//        String redisDataStr = stringRedisTemplate.opsForValue().get(key);
//
//
//        //如果redis为空，直接返回null
//        if(StrUtil.isBlank(redisDataStr)){
//            return null;
//        }
//        //当前redis中的店铺数据data
//        // 先填充 RedisData 对象
//        RedisData redisData = JSONUtil.toBean(redisDataStr, RedisData.class);
//        // 从 RedisData 对象中获取 Shop 数据
//        Shop data = JSONUtil.toBean(redisData.getData().toString(), Shop.class);
//        log.info("data为{}", data);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        //未过期，直接返回数据
//        if(expireTime.isAfter(LocalDateTime.now())){
//            return data;
//        }
//
//        //过期，缓存重建
//        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
//        Shop shop = null;
//
//        try {
//            //尝试获取锁
//            boolean isLock = tryLock(lockKey);
//            //没获取到锁
//            if (! isLock) {
//                //获取旧数据，返回
//                return data;
//            }
//            //获取到锁后再次判断是否过期
//            expireTime = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(key), RedisData.class).getExpireTime();
//            if(expireTime.isAfter(LocalDateTime.now())){
//                return data;
//            }
//            //获取到锁,开启新线程，将要更新的信息发送到redis中
//            CACHE_REBUILD_EXECUTOR.submit(() -> {
//               this.saveShop2Redis(id, 20L);
//            });
//
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        } finally {
//            //释放锁
//            unlock(lockKey);
//        }
//
//        //返回过期的店铺信息
//        return data;
//
//    }



    //缓存击穿(使用互斥锁）
    public Shop queryWithMutex(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        Map<Object, Object> shopMap = stringRedisTemplate.opsForHash()
                .entries(key);
        if(! shopMap.isEmpty() && ! shopMap.containsKey("")){
            return BeanUtil.fillBeanWithMap(shopMap, new Shop(), false);
        }
        if(shopMap.containsKey("")){
            return null;
        }
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;

        try {
            //尝试获取锁
            boolean isLock = tryLock(lockKey);
            //没获取到锁
            if (! isLock) {
                //休眠，重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取到锁
            shop = getById(id);
            if(shop == null){
                //将空值写入redis
                stringRedisTemplate.opsForHash().put(key, "", "");
                //设置过期时间为两分钟
                stringRedisTemplate.expire(key, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回错误值
                return null;
            }
            Map<String, Object> map = BeanUtil.beanToMap(shop, new HashMap<>(), CopyOptions.create()
                    .setIgnoreNullValue(true)
                    .setFieldValueEditor((fieldName, fieldValue) -> fieldValue == null ? null : fieldValue.toString()));
            stringRedisTemplate.opsForHash().putAll(key, map);
            stringRedisTemplate.expire(key, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unlock(lockKey);
        }

        return shop;

    }
    //获取互斥锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //删除互斥锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    //将店铺信息和逻辑过期时间封装后添加到redis
    public void saveShop2Redis(Long id, Long expireSeconds){
        //根据id查询商铺信息
        Shop shop = getById(id);

        //封装redisData
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        //将数据添加到redis
        String jsonStr = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr);
    }

    /**
     * 更新数据库后删除缓存
     * @param shop
     * @return
     */
    @Transactional
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空！");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        //1.判断是否需要根据坐标查询
        if(x == null || y ==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            log.info("查询结果：{}", page.getRecords());
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3.查询redis、按照距离排序分页，结果返回shopId 、distance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        //4.解析商铺id
        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        if(content.size() < from){
            return Result.ok(Collections.emptyList());
        }
        //4.1截取from-end的部分
        List<Long> ids = new ArrayList<>(content.size());
        Map<String, Distance> distanceMap = new HashMap<>();
        content.stream().skip(from).forEach(result -> {
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        //5.根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> list = query().in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        for (Shop shop : list) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(list);
    }

}
